﻿using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.AllocateCommand;
using WarehouseManagement.Infrstructre.Interface;

namespace WarehouseManagement.Application.CommandHandler.AllocateCommandHandler
{
    /// <summary>
    /// 删除仓库调拨命令处理器
    /// </summary>
    public class AllocateDelCommandHandler : IRequestHandler<AllocateDelCommand, int>
    {
        private readonly IAllocateRepository _allocateRep;
        private readonly IAllocationProductsRepository _allocationProductsRep;
        private readonly ISqlSugarClient db;

        public AllocateDelCommandHandler(IAllocateRepository allocateRep, IAllocationProductsRepository allocationProductsRep, ISqlSugarClient db)
        {
            _allocateRep = allocateRep;
            _allocationProductsRep = allocationProductsRep;
            this.db = db;
        }

        public async Task<int> Handle(AllocateDelCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                var list = (await _allocateRep.GetAll()).Where(x => request.AllocateId.Contains(x.AllocateId)).ToList();
                foreach (var material in list)
                {
                    material.IsDel = true;
                    material.DelName = request.DelName;
                    material.DelTime = DateTime.Now;
                    var item = (await _allocationProductsRep.GetAll()).Where(x => x.ANumber == material.ANumber).ToList();
                    foreach (var subpiece in item)
                    {
                        subpiece.IsDel = true;
                        subpiece.DelName = request.DelName;
                        subpiece.DelTime = DateTime.Now;
                        await _allocationProductsRep.UpdateAsync(subpiece);
                    }
                    await _allocateRep.UpdateAsync(material);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw ex;
            }
            finally
            {
                db.Ado.Close();
            }
            return 1;
        }
    }
}
